<script setup>
import * as echarts from 'echarts'
import { ref, reactive, onMounted } from 'vue';
import { datetimeToString, dateIntervalDays } from '@/utils/datetimeUtils'
import { GetAuthVariety, CalculateSpreadArbitrage } from '@/api/futureTools/spreadArbitrage'

const varietyData = ref([])
const chartOneBox = ref(null)
const chartTwoBox = ref(null)
const chartThreeBox = ref(null)
let chartOne = null
let chartTwo = null
let chartThree = null

const myArbitrage = reactive({
  selectId: null,
  arbitrageList: [],
})

const arbitrageConfig = reactive({
  configList: [],
  startDate: null,
  endDate: null,
  lastYears: 1,
  saveName: '',
  calculating: false,
})

const changeLastYears = (years) => {
  arbitrageConfig.lastYears = years
  arbitrageConfig.endDate = datetimeToString(new Date())
  arbitrageConfig.startDate = dateIntervalDays(new Date(), -365 * years)
}

const varietySelectChange = (configIndex) => {
  const vcode = arbitrageConfig.configList[configIndex].vcode
  console.log(vcode)
  for (let i = 0; i < varietyData.value.length; i++) {
    if (varietyData.value[i].code === vcode) {
      arbitrageConfig.configList[configIndex].contractList = varietyData.value[i].delivery
      arbitrageConfig.configList[configIndex].multiplier = varietyData.value[i].multiplier
      arbitrageConfig.configList[configIndex].vname = varietyData.value[i].name
      break;
    }
  }
}

const contractSelectChange = (configIndex) => {
  const cfg = arbitrageConfig.configList[configIndex]
  for (let i = 0; i < cfg.contractList.length; i++) {
    if (cfg.contractList[i].id === cfg.contract) {
      console.log( cfg.contractList[i])
      cfg.db_name = cfg.contractList[i].db_name
      cfg.tb_name = cfg.contractList[i].tb_name
      cfg.dat_name = cfg.contractList[i].dat_name
      break;
    }
  }
}

const calculateSpreadArbitrage = () => {
  console.log(arbitrageConfig)
  let config_items = []
  for(let i = 0; i < arbitrageConfig.configList.length; i++) {
    const c_obj = arbitrageConfig.configList[i]
    config_items.push({
      vcode: c_obj.vcode,
      vname: c_obj.vname,
      contract: c_obj.contract,
      series_name: c_obj.dat_name,
      db_name: c_obj.db_name,
      tb_name: c_obj.tb_name,
      multiplier: c_obj.multiplier,
      volume: c_obj.volume,
      direction: c_obj.direction
    })
  }
  const config_org = {
    start_date: arbitrageConfig.startDate,
    end_date: arbitrageConfig.endDate,
    last_years: arbitrageConfig.lastYears,
    config_items,
  }
  console.log(config_org)
  CalculateSpreadArbitrage(config_org).then((res) => {
    console.log(res)
    const season_opt = res.data.season_opt
    chartTwo.setOption(season_opt, { notMerge: true })
    const basic_opt = res.data.basic_opt
    chartOne.setOption(basic_opt, { notMerge: true })
    const profit_opt = res.data.profit_opt
    chartThree.setOption(profit_opt, { notMerge: true })
    
  })
}

onMounted(() => {
  arbitrageConfig.configList.push(
    { vcode: null, contract: null, direction: 'B', volume: 1, multiplier: 1, contractList: [], db_name: '', tb_name: ''},
    { vcode: null, contract: null, direction: 'S', volume: 1, multiplier: 1, contractList: [], db_name: '', tb_name: ''},
  )
  arbitrageConfig.endDate = datetimeToString(new Date())
  arbitrageConfig.startDate = dateIntervalDays(new Date(), -365)

  GetAuthVariety().then((res) => {
    console.log(res)
    varietyData.value = res.data
  })

  chartOne = echarts.init(chartOneBox.value) // [指定图形渲染的dom]
  chartTwo = echarts.init(chartTwoBox.value) 
  chartThree = echarts.init(chartThreeBox.value)
})

</script>
<template>
  <div class="page-view">
    <div class="action-box">
      <el-select
        v-model="myArbitrage.selectId"
        placeholder="选择我的套利，快捷查看"
        size="default"
        style="width: 300px"
      >
        <el-option
          v-for="item in myArbitrage.arbitrageList"
          :key="item.id"
          :value="item.id"
          :label="item.name"
        />
      </el-select>
      <div class="right-action">
        <el-input
          v-model="arbitrageConfig.saveName"
          show-word-limit
          class="save-name-input"
          size="default"
          placeholder="为当前套利配置取一个名称，并保存起来"
          :maxlength="30"
          :minlength="1"
        />
        <el-button
          icon="Collection"
          type="primary"
          size="default"
        >
          保存
        </el-button>
      </div>
    </div>
    <div class="config-box">
      <div
        v-for="(rc, index) in arbitrageConfig.configList"
        :key="index"
        class="row-config"
      >
        <el-select
          v-model="rc.vcode"
          placeholder="请选择品种"
          style="width: 300px"
          size="default"
          filterable
          @change="varietySelectChange(index)"
        >
          <el-option  
            v-for="v in varietyData"
            :key="v.code"
            :value="v.code"
            :label="`${v.name} (${v.code})`"
          />
        </el-select>
        <el-select
          v-model="rc.contract"
          placeholder="请选择交割月"
          size="default"
          style="margin-left: 10px; width: 220px"
          @change="contractSelectChange(index)"
        >
          <el-option  
            v-for="v in rc.contractList"
            :key="v.id"
            :value="v.id"
            :label="v.dat_name"
          />
        </el-select>
        <el-switch
          v-model="rc.direction"
          inline-prompt
          size="default"
          style="--el-switch-on-color: #ff4949; --el-switch-off-color: #13ce66; margin-left: 10px"
          active-text="多"
          active-value="B"
          inactive-text="空"
          inactive-value="S"
        />
        <el-input-number
          v-model="rc.volume"
          placeholder="手数"
          size="default"
          class="config-volume"
          controls-position="right"
          :min="1"
        />
        <div class="volume-text">手</div>
      </div>
    </div>
    <div class="datecfg-box">
      <el-date-picker
        v-model="arbitrageConfig.startDate"
        type="date"
        size="default"
        placeholder="开始日期"
        value-format="YYYY-MM-DD"
        :clearable="false"
      />
      <span style="margin: 0 10px;">至</span>
      <el-date-picker
        v-model="arbitrageConfig.endDate"
        type="date"
        size="default"
        placeholder="结束日期"
        value-format="YYYY-MM-DD"
        :clearable="false"
      />
      <el-button-group
        style="margin-left: 10px"
        size="default"
      >
        <el-button
          :type="arbitrageConfig.lastYears === 1 ? 'primary': ''"
          @click="changeLastYears(1)"
        >
          近1年
        </el-button>
        <el-button
          :type="arbitrageConfig.lastYears === 3 ? 'primary': ''"
          @click="changeLastYears(3)"
        >
          近3年
        </el-button>
        <el-button 
          :type="arbitrageConfig.lastYears === 5 ? 'primary': ''"
          @click="changeLastYears(5)"
        >
          近5年
        </el-button>
      </el-button-group>
      <el-button
        type="warning"
        size="default"
        style="margin-left: 30px"
        icon="Calendar"
        :loading="arbitrageConfig.calculating"
        @click="calculateSpreadArbitrage"
      >
        开始计算
      </el-button>
    </div>
    <div class="c-box">
      <div class="chart-box" ref="chartOneBox"></div>
      <div class="tip">注：价差=做空合约价格-做多合约价格</div>
    </div>
    <div class="chart-box" ref="chartTwoBox"></div>
    <div class="c-box">
      <div class="chart-box" ref="chartThreeBox"></div>
      <div class="tip">注：收益是指第一日按设置操作，分别到当日能达到的收益值。</div>
    </div>
  </div>
</template>
<style scoped lang="scss">
.page-view {
  padding: 10px;
  .action-box {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: 4px;
    padding: 10px;
    .right-action {
      display: flex;
      align-items: center;
      margin-left: auto;
      .save-name-input {
        margin-right: 10px;
        width: 330px;
      }
    }
    
  }
  .config-box {
    background-color: #fff;
    border-radius: 4px;
    padding: 10px;
    margin-top: 10px;
    .row-config {
      display: flex;
      align-items: center;
      margin-top: 10px;
      .config-volume {
        margin-left: 10px;
        width: 100px;
      }
      .volume-text {
        margin-left: 10px;
        font-size: 15px;
        font-weight: 600;
      }
    }
  }
  .datecfg-box {
    background-color: #fff;
    border-radius: 4px;
    padding: 10px;
    margin-top: 10px;
  }
  .chart-box {
    margin-top: 10px;
    background-color: #fff;
    padding: 10px;
    height: 340px;
    border-radius: 4px;
  }
  .c-box {
    margin-top: 10px;
    padding: 10px;
    background-color: #fff;
    .tip {
      font-size: 13px;
      color: #555;
    }
  }
}
</style>
